package com.ict.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ict.common.core.domain.entity.SysDept;
import com.ict.common.utils.SecurityUtils;
import com.ict.common.utils.StringUtils;
import com.ict.common.utils.bean.BeanUtils;
import com.ict.common.utils.uuid.IdUtils;
import com.ict.system.mapper.SysUserRoleMapper;
import com.ict.system.service.ISysDeptService;
import com.ict.web.constant.Constants;
import com.ict.web.constant.ProjectStatusEnum;
import com.ict.web.controller.file.domain.YzqFile;
import com.ict.web.controller.file.service.IYzqFileService;
import com.ict.web.domain.*;
import com.ict.web.dto.MilestoneInformationAddDto;
import com.ict.web.dto.MilestoneInformationDto;
import com.ict.web.mapper.MilestoneInformationMapper;
import com.ict.web.msg.domain.SysMsg;
import com.ict.web.msg.util.CreateMsgUtil;
import com.ict.web.service.*;
import com.ict.web.utils.pdf.PdfUtil;
import com.ict.web.vo.MilestoneInformationFinishTimeVo;
import com.ict.web.vo.MilestoneInformationVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 里程碑信息--刘杰Service业务层处理
 *
 * @author ruoyi
 * @date 2022-03-01
 */
@Service
public class MilestoneInformationServiceImpl extends ServiceImpl<MilestoneInformationMapper,MilestoneInformation> implements IMilestoneInformationService
{
    @Resource
    private MilestoneInformationMapper milestoneInformationMapper;
    @Autowired
    private IProjectManagementService projectManagementService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IApprovalService approvalService;
    @Autowired
    private IReviewTaskService reviewTaskService;
    @Autowired
    private IYzqFileService fileService;
    @Autowired
    private IMilestoneInformationRelationService milestoneInformationRelationService;
    @Resource
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private IContractInformationService contractInformationService;
    /**
     * 查询里程碑信息--刘杰
     *
     * @param milepostId 里程碑信息--刘杰主键
     * @return 里程碑信息--刘杰
     */
    @Override
    public MilestoneInformation selectMilestoneInformationByMilepostId(Long milepostId)
    {
        return milestoneInformationMapper.selectMilestoneInformationByMilepostId(milepostId);
    }

    /**
     * 查询里程碑信息--刘杰列表
     *
     * @param milestoneInformation 里程碑信息--刘杰
     * @return 里程碑信息--刘杰
     */
    @Override
    public List<MilestoneInformation> selectMilestoneInformationList(MilestoneInformation milestoneInformation)
    {
        return milestoneInformationMapper.selectMilestoneInformationList(milestoneInformation);
    }
    /**
     * 查询该项目的里程碑
     *
     * @param proId
     * @return 里程碑信息--刘杰
     */
    @Override
    public List<MilestoneInformationVo> selectMilestoneInformationByProId(Long proId)
    {
        List<MilestoneInformation> milestoneInformationList = milestoneInformationMapper.selectMilestoneInformationByProId(proId);
        List<MilestoneInformationVo> list = new ArrayList<>();
        milestoneInformationList.stream().forEach(s->{
            MilestoneInformationVo milestoneInformationVo = new MilestoneInformationVo();
            BeanUtils.copyProperties(s,milestoneInformationVo);
            YzqFile file = fileService.getById(s.getEnclosure());
            if(StringUtils.isNotNull(file)){
                milestoneInformationVo.setEnclosureFile(file);
            }
            list.add(milestoneInformationVo);
        });
        return list;
    }
    /**
     * 新增里程碑信息--刘杰
     *
     * @param dto 里程碑信息--刘杰
     * @return 结果
     */
    @Override
    public int insertMilestoneInformation(MilestoneInformationAddDto dto)
    {
        List<MilestoneInformationDto> list = dto.getMilestoneInformationList();
        Assert.isTrue(StringUtils.isNotEmpty(list),"里程碑新增集合不能为空");
        List<MilestoneInformation> milestoneInformationList = new ArrayList<>();
        List<YzqFile> fileList= new ArrayList<>();
        list.stream().forEach(bean->{
            MilestoneInformation milestoneInformation = MilestoneInformationAddDto.of(bean);
            //存储合同扫码件文件
            YzqFile contractFile = bean.getEnclosure();
            if(StringUtils.isNotEmpty(contractFile.getFileName())){
                contractFile.setId(String.valueOf(IdUtils.snowId()));
                contractFile.setDelFlag(ExtractExpert.DELETE_STATUS_NORMAL);
                fileList.add(contractFile);
                milestoneInformation.setEnclosure(contractFile.getId());
            }
            milestoneInformationList.add(milestoneInformation);
        });

        //新增里程碑信息-生成对应系统消息
        SysDept sysDept = deptService.selectDeptById(SecurityUtils. getDeptId());
        ProjectManagement projectManagement = projectManagementService.getById(dto.getProId());
        Assert.isTrue(StringUtils.isNotNull(projectManagement),"未找到该项目信息");
        String content=projectManagement.getNickName()+ CreateMsgUtil.SUBMITTED+projectManagement.getName()+CreateMsgUtil.MILESTONE_MANAGEMENT_SUBMITTED;
        //大数据局收到消息
        List<Long> bigDataId = userRoleMapper.getUserIdByRoleId(Constants.ROLE_TYPE_BIGDATA);
        List<Long> bigDataNormalId = userRoleMapper.getUserIdByRoleId(Constants.ROLE_TYPE_BIGDATA_NORMAL);
        bigDataId.addAll(bigDataNormalId);
        bigDataId.forEach(s->{
            CreateMsgUtil.createMsg(content,s,null,CreateMsgUtil.MILESTONE_MANAGEMENT_SUBMITTED_TITLE, SysMsg.RESOURCE_TYPE_DATA,null,null);
        });

        ReviewTask reviewTask = reviewTaskService.getById(projectManagement.getReviewTaskId());
        Assert.isTrue(StringUtils.isNotNull(reviewTask),"评审任务不能为空");
        Approval approval = approvalService.getApproval(projectManagement.getProId(), projectManagement.getIsState(),null,null);
        approval.setApprovalNode(ProjectStatusEnum.MILESTONE_MANAGEMENT_SUBMITTED.get().getNode());
        approval.setApprovalStage(ProjectStatusEnum.MILESTONE_MANAGEMENT_SUBMITTED.get().getStage());
        approval.setApprovalStatus(ProjectStatusEnum.MILESTONE_MANAGEMENT_SUBMITTED.get().getStatus());
        approval.setEndTime(LocalDateTime.now());
        approval.setApprovalOperator(SecurityUtils.getNickName());
        projectManagement.setIsState(ProjectStatusEnum.COMPLIANCE_REVIEW_TO_BE_SUBMITTED.get().getStatus());
        projectManagement.setNode(ProjectStatusEnum.COMPLIANCE_REVIEW_TO_BE_SUBMITTED.get().getNode());
        projectManagement.setStag(ProjectStatusEnum.COMPLIANCE_REVIEW_TO_BE_SUBMITTED.get().getStage());
        //新增合规审查待提交
        approvalService.save(new Approval(IdUtils.snowId(),projectManagement.getProId(),ProjectStatusEnum.COMPLIANCE_REVIEW_TO_BE_SUBMITTED.get().getStage(),
                ProjectStatusEnum.COMPLIANCE_REVIEW_TO_BE_SUBMITTED.get().getNode(), LocalDateTime.now(),null, null,ProjectStatusEnum.COMPLIANCE_REVIEW_TO_BE_SUBMITTED.get().getStatus(),
                "/",null, null,null, LocalDateTime.now(),Approval.APPROVAL_TYPE_PROJECT_MANAGE));
        reviewTask.setNode(ProjectStatusEnum.COMPLIANCE_REVIEW_TO_BE_SUBMITTED.get().getNode());
        reviewTask.setNodeStatus(ProjectStatusEnum.COMPLIANCE_REVIEW_TO_BE_SUBMITTED.get().getStatus());
        projectManagementService.updateById(projectManagement);
        reviewTaskService.updateById(reviewTask);
        approvalService.updateById(approval);
        milestoneInformationMapper.batchInsert(milestoneInformationList);
        //批量导入文件对象/里程碑对象/里程碑与项目管理关系对象
        List<Long> collect = milestoneInformationList.stream().map(MilestoneInformation::getMilepostId).collect(Collectors.toList());
        if(StringUtils.isNotEmpty(fileList)){
            fileService.batchInsertFile(fileList);
        }
        //同步项目数据到项目信息表中
        approvalService.synchronizationProjectInfo(projectManagement);
        return milestoneInformationRelationService.batchInsert(dto.getProId(),collect);
    }

    /**
     * 修改里程碑信息--刘杰
     *
     * @param dto 里程碑信息--刘杰
     * @return 结果
     */
    @Override
    public int updateMilestoneInformation(MilestoneInformationAddDto dto)
    {
        List<MilestoneInformationRelation> milestoneInformationRelations = milestoneInformationRelationService.lambdaQuery()
                .eq(MilestoneInformationRelation::getProId, dto.getProId()).list();
        List<Long> collect = milestoneInformationRelations.stream().map(MilestoneInformationRelation::getMilepostId).collect(Collectors.toList());
        QueryWrapper<MilestoneInformationRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pro_id",dto.getProId());
        milestoneInformationRelationService.remove(queryWrapper);
        milestoneInformationMapper.deleteBatchIds(collect);

        List<MilestoneInformationDto> list = dto.getMilestoneInformationList();
        Assert.isTrue(StringUtils.isNotEmpty(list),"里程碑新增集合不能为空");
        List<MilestoneInformation> milestoneInformationList = new ArrayList<>();
        List<YzqFile> fileList= new ArrayList<>();
        list.stream().forEach(bean->{
            MilestoneInformation milestoneInformation = MilestoneInformationAddDto.of(bean);
            //存储合同扫码件文件
            YzqFile contractFile = bean.getEnclosure();
            contractFile.setId(String.valueOf(IdUtils.snowId()));
            contractFile.setDelFlag(ExtractExpert.DELETE_STATUS_NORMAL);
            fileList.add(contractFile);
            milestoneInformation.setEnclosure(contractFile.getId());
            milestoneInformationList.add(milestoneInformation);
        });
        milestoneInformationMapper.batchInsert(milestoneInformationList);
        //批量导入文件对象/里程碑对象/里程碑与项目管理关系对象
        List<Long> collect1 = milestoneInformationList.stream().map(MilestoneInformation::getMilepostId).collect(Collectors.toList());
        fileService.batchInsertFile(fileList);
        return milestoneInformationRelationService.batchInsert(dto.getProId(),collect1);

    }

    /**
     * 删除里程碑信息--刘杰信息
     *
     * @param milepostId 里程碑信息--刘杰主键
     * @return 结果
     */
    @Override
    public int deleteMilestoneInformationByMilepostId(Long milepostId)
    {
        MilestoneInformation bean = milestoneInformationMapper.selectById(milepostId);
        bean.setDelFlag("1");
        return milestoneInformationMapper.updateById(bean);
    }

    @Override
    public MilestoneInformationFinishTimeVo finishTime(Long projectId) {
        MilestoneInformationFinishTimeVo milestoneInformationFinishTimeVo = new MilestoneInformationFinishTimeVo();


        List<Approval> approvalList = approvalService.lambdaQuery().eq(Approval::getProjectId, projectId)
                .eq(Approval::getApprovalNode, ProjectStatusEnum.SCHEME_DECLARATION_TO_BE_SUBMITTED.get().getNode())
                .orderByDesc(Approval::getCreateTime).list();

        if(StringUtils.isNotEmpty(approvalList)){
            milestoneInformationFinishTimeVo.setApplicationApprovalTime(approvalList.get(0).getCreateTime().format(PdfUtil.fmt));
        }

        LambdaQueryWrapper<Approval> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Approval::getProjectId,projectId)
                .eq(Approval::getApprovalNode,ProjectStatusEnum.FINANCIAL_APPROVAL_AND_FILING_TO_BE_REVIEWED.get().getNode());
        Approval approval1 = approvalService.getOne(queryWrapper1);
        milestoneInformationFinishTimeVo.setProgramApprovalTime(approval1.getCreateTime().format(PdfUtil.fmt));
        ProjectManagement projectManagement = projectManagementService.getById(projectId);
        //初设方案审核通过时间
        milestoneInformationFinishTimeVo.setPreliminaryDesignSchemeApprovalTime(approval1.getCreateTime().format(PdfUtil.fmt));
        //合同备案的签约时间
        ContractInformation contractInformation = contractInformationService.getById(projectManagement.getContractId());
        LocalDateTime localDateTime = contractInformation.getSigningTime().toInstant()
                .atZone( ZoneId.systemDefault() )
                .toLocalDateTime();
        milestoneInformationFinishTimeVo.setSigningTime(localDateTime.toString().replace("T"," "));
        return milestoneInformationFinishTimeVo;
    }
}
